package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.Dto.OrdersDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



/**
 * @author zhoufei
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /**
     * 用户下单
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info(orders.toString());
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 后台订单明细分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime){
        log.info("订单明细分页查询");
        //1.创造分页构造器对象
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //2.构造条件查询对象
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number != null,Orders::getId,number);
        queryWrapper.between((beginTime!=null && endTime!=null),Orders::getOrderTime,beginTime,endTime);
        ordersService.page(pageInfo, queryWrapper);

        return  R.success(pageInfo);
    }

    /**
     * 修改订单状态
     * @return
     */
    @PutMapping
    public R updateOrdersStatus(@RequestBody Orders orders){
        //1.获取订单id
        Long id = orders.getId();
        //2根据id修改订单状态
            //2.1获取需要修改的订单状态
            Integer status = orders.getStatus();
            //2.2进行条件修改
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Orders::getId,id);
            updateWrapper.set(Orders::getStatus,status);
        //3.执行查询，返回结果
        ordersService.update(updateWrapper);

        return R.success("订单状态修改成功");
    }

    /**
     * 用户端订单分页查询
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){

        Page<OrdersDto> dtoOrdersPage = ordersService.getUserOrders(page,pageSize);

        return R.success(dtoOrdersPage);
    }
}
